<?php
namespace Sys\Controller;
use Todo\Controller\ApiController;
use Todo\Service\DictService;

class DictController extends ApiController {

    /**
     * 自定义查询条件
     * @param array &$where 丢生成的查询条件
     */
    protected function _filter(&$where){
        $keywords = I('request.keywords');
        if($keywords){
            $where['title'] = array('like', '%'.$keywords.'%');
        }
    }

    /**
     * 格式化数据的JS
     */
    public function format(){
        $this->_loadModel();
        $list = $this->_model->findAll();
        foreach ($list as &$dict){
            $map = array();
            $lines = explode("\n", $dict['value']);
            foreach ($lines as $line){
                if(!$line) continue;
                $cols = explode('=', $line);
                if(count($cols) < 2) continue;
                $map[trim($cols[0])] = trim($cols[1]);
            }
            $dict['map'] = $map;
        }
        $this->assign('list', $list);
        $this->display('format', 'utf-8', 'application/javascript');
    }

    /**
     * 单个字典
     */
    public function info(){
        $code = I('get.code');
        if(!$code) $this->apiError('参数不完整');

        $data = DictService::getInstance()->getDict($code);
        if(!$data) $this->apiError('数据不存在');

        $map = array();
        foreach ($data['map'] as $k => $v){
            $map[] = array(
                'id' => $k,
                'title' => $v
            );
        }
        $this->apiData($map);
    }
}